import axios from 'axios';
import { ElMessage } from 'element-plus';
import { localClear } from '@/utils/local-util';
import { sessionClear } from '@/utils/session-util';
import { useUserStore } from '@/store/system/user';
import { menuStore } from '@/store/system/menu';
import { pageTagStore } from '@/store/system/page-tag';

// token消息头
// const TOKEN_HEADER = 'x-access-token';
const TOKEN_HEADER = 'Authorization';


// 创建axios对象
const Axios = axios.create({
    // 添加proxy代理的key
    baseURL:import.meta.env.VITE_APP_API_KEY,
});

// ========================= 请求拦截器 =========================
Axios.interceptors.request.use(
    (config) => {
        const token = useUserStore().token;
        if(token) {
            // 每次请求的时候携带token
            config.headers[TOKEN_HEADER] = token;
        }else {
            delete config.headers[TOKEN_HEADER];
        };
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// ========================= 响应拦截器 =========================
Axios.interceptors.response.use(
    (response) =>{
        const res = response.data; // 对响应数据做点什么
        if(res.code && res.code !== 200) {
            // 401 token错误 4001已在别处登录
            if(res.code === 401 || res.code === 4001) {
                ElMessage({
                    showClose: true,
                    message: '您没有登录，请重新登录',
                    type: 'error'
                });
                // 重置用户缓存信息
                useUserStore().$reset();
                menuStore().$reset();
                pageTagStore().$reset();
                localClear();
                sessionClear();
                setTimeout(() => { //跳转到登录页面，直接使用页面刷新的策略
                    location.href = '/';
                }, 300);
                return Promise.reject(response);
            };
            ElMessage({
                showClose: true,
                message: res.msg,
                type: 'error'
            });
            return Promise.resolve(res);
        } else {
            return Promise.resolve(res);
        }
    },
    (error) => {
        console.log(error)
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage({
                showClose: true,
                message: '网络超时',
                type: 'error'
            });
        } else if (error.message == 'Network Error') {
            ElMessage({
                showClose: true,
                message: '网络连接错误',
                type: 'error'
            });
        } else if(error.response.status == '401' && error.response.statusText == 'Unauthorized') {
            ElMessage({
                showClose: true,
                message: '登录时效已过期，请重新登录',
                type: 'error'
            });
            useUserStore().$reset(); 
            localClear();
            sessionClear();
            setTimeout(() => { //跳转到登录页面，直接使用页面刷新的策略
                location.href = '/';
            }, 300);
        } else if (error.message.indexOf('Request') != -1) {
            ElMessage({
                showClose: true,
                message: '网络发生错误',
                type: 'error'
            });
        };
        return Promise.reject(error);
    }
);

// ========================= 对外提供方法，get和post，下载download等 =========================/**
/* 
* 通用请求封装
* @param config
*/
export const request = (config) => {
    return Axios.request(config);
};
 
/**
* post请求
*/
export const postRequest = (url, data, urlType) => {
    return request({ 
        data, 
        url, 
        urlType,
        method: 'post'
    });
};
 
/**
* get请求
*/
export const getRequest = (url, params, urlType) => {
    return request({ 
        url, 
        params,
        urlType,
        method: 'get', 
    });
};

/**
* delete请求 
* 
*/
export const deleteRequest = (url, params, urlType) => {
   return request({ 
        url, 
        params,
        urlType,
        method: 'delete'
    });
};

/**
 * 文件下载 
 * 
*/